package com.fm.parser.excel;

import com.fm.base.factory.ClassFactory;
import com.fm.structure.base.Pair;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author finalmachine
 */
public abstract class AbstractExcelMapHandler<T extends Map<String, Object>> implements ExcelRowHandler {
    protected LinkedHashMap<String, String> headers = new LinkedHashMap<>();
    protected ClassFactory<T> factory;

    protected AbstractExcelMapHandler(ClassFactory<T> factory) {
        this.factory = factory;
    }

    @Override
    public void doRow(int rowNum, List<Pair<String, Object>> cells) {
        if (rowNum == 1) {
            Set<String> headersCheck = new HashSet<>(cells.size());
            for(Pair<String, Object> cell : cells) {
                if (!headersCheck.add(cell.getRight().toString())) {
                    throw new RuntimeException("重复的表头" + cell);
                }
                headers.put(cell.getLeft().replaceAll("\\d+$", ""), cell.getRight().toString());
            }
            doFirstRow(headers.values());
        } else {
            T map = factory.get();
            for(Pair<String, Object> cell : cells) {
                map.put(headers.get(cell.getLeft().replaceAll("\\d+$", "")), cell.getRight());
            }
            doOtherRow(rowNum, map);
        }
    }

    /**
     * do with the excel first row
     *
     * @param row the first row
     */
    protected abstract void doFirstRow(Collection<String> row);

    /**
     * do with the excel others row
     *
     * @param rowNum 1 base but first is the headers
     * @param map    key-value pair
     */
    protected abstract void doOtherRow(int rowNum, T map);
}
